package com.only4play.captcha;

import com.only4play.common.constants.ErrorCodeEnum;
import com.only4play.common.exception.ApplicationException;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Base64;

/**
 * @author liyuncong
 * @version 1.0
 * @file CaptchaPayload
 * @brief CaptchaPayload
 * @details CaptchaPayload
 * @date 2024-02-20
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2024-02-20               liyuncong          Created
 */

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class CaptchaPayload implements Serializable {

    private byte[] image;
    private String randomKey;
    private String code;
    private long expireTime;
    private CaptchaConfig config;

    public CaptchaPayload(
        BufferedImage image, String randomKey, String code, long expireIn, CaptchaConfig config
    ) {
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        try {
            //写入流中
            ImageIO.write(image, config.getImgFormat(), byteStream);
        } catch (IOException exception) {
            throw new ApplicationException(ErrorCodeEnum.SERVER_ERROR, exception);
        }
        //转换成字节
        this.image = byteStream.toByteArray();
        this.randomKey = randomKey;
        this.code = code;
        this.expireTime = expireIn;
        this.config = config;
    }

    public String base64() {
        //转换成base64串
        String base64 = Base64.getEncoder().encodeToString(image).trim();
        //删除 \r\n
        base64 = base64.replaceAll("\n", "").replaceAll("\r", "");

        return config.getBase64Prefix() + base64;
    }

//    /**
//     * 验证是否过期.
//     */
//    public boolean isExpire() {
//        return LocalDateTime.now().isAfter(expireTime);
//    }
}
